package pkg

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"log"
	"net/http"
	"time"
)

type MyCustomClaims struct {
	UserId uint `json:"userId"`
	jwt.RegisteredClaims
}

func CreateJwtToken(userId uint, duration time.Duration, secret string) (string, error) {
	claims := MyCustomClaims{
		userId,
		jwt.RegisteredClaims{
			// A usual scenario is to set the expiration time relative to the current time
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(duration)),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString([]byte(secret))
	fmt.Println(ss, err)
	return ss, err
}

func ParseJwtToken(secret string) gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("userId")
		if tokenString == "" {
			c.JSON(http.StatusOK, gin.H{
				"code":    1000,
				"message": "未登录",
				"data":    nil,
			})
			c.Abort()
			return
		}
		token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (any, error) {
			return []byte(secret), nil
		})
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    1000,
				"message": "非法token",
				"data":    nil,
			})
			log.Fatal(err)
			c.Abort()
			return
		}
		claims, _ := token.Claims.(*MyCustomClaims)

		if claims.UserId == 0 {
			c.JSON(http.StatusOK, gin.H{
				"code":    1000,
				"message": "toke解析失败",
				"data":    nil,
			})
			c.Abort()
			return
		}

		c.Set("userId", claims.UserId)
		fmt.Println(claims.UserId)
	}

}
